<template>
	<view class="comment">
		<u-empty v-show="!isData" mode="comment" icon="http://cdn.uviewui.com/uview/empty/comment.png"></u-empty>

		<template v-show="isData">
			<template v-for="incomingItem in levelCommentData" :keys="incomingItem._id">
				<comment-item :receiveCommentObj="incomingItem" :userId="receiveCommentObj.user_id"
					replyBtnVbt></comment-item>
			</template>
		</template>

	</view>
</template>

<script>
	import commentItem from "./cpns/comment-item/comment-item.vue"
	import {
		userField
	} from "@/config/index.config.js"
	import {
		isLogin
	} from "../../utils/common"

	const db = uniCloud.database()
	const commentTb = db.collection('comment')
	const userTb = db.collection('uni-id-users')

	export default {
		name: "comment",
		components: {
			commentItem,
		},
		props: {
			receiveCommentObj: {
				type: Object,
				default: () => {
					return {

					}
				}
			},
		},
		created() {
			console.log("created-commentComponent");
			uni.$on("updateCommentQuantity", this.updateQuantity)
			this.getLevelComment()
		},
		data() {
			return {
				isData: false,
				levelCommentData: [],
			};
		},
		methods: {
			updateQuantity(id) {
				let index = this.levelCommentData.findIndex(item => {
					return item._id == id
				})
				// debugger
				let tempObj = this.levelCommentData[index]
				tempObj.totalReply += 1
				this.levelCommentData.splice(index, 1, tempObj)
			},
			unshiftComment(data) {
				this.isData = true
				this.levelCommentData.unshift(data)
				// debugger
				console.log('unshift');
				console.log(this.levelCommentData);
			},
			async getLevelComment() {
				try {
					const commentTempTb = commentTb.where(
							`article_id=='${this.receiveCommentObj.article_id}' && comment_type==0`)
						.getTemp()

					const userTempTb = userTb.field(userField).getTemp()

					const res = await db.collection(commentTempTb, userTempTb).orderBy('comment_date desc').get()

					await this.getCount(res)

					this.levelCommentData = res.result.data
					if (res.result.data.length) this.isData = true

					console.log({
						res
					});


				} catch (e) {
					console.log('评论失败', e);
					uni.showToast({
						title: "评论获取失败",
						icon: "none"
					})
				}
			},
			async getCount(res) {
				let idArr = res.result.data.map(item => {
					return item._id
				})

				let replyArr = await db.collection("comment").where({
						reply_comment_id: db.command.in(idArr)
					}).groupBy('reply_comment_id')
					.groupField('count(*) as totalReply').get();


				res.result.data.forEach(item => {
					item.totalReply = 0
					let obj = replyArr.result.data.find(find => {
						return find.reply_comment_id == item._id
					})
					// console.log({
					// 	obj
					// });
					if (obj) item.totalReply = obj.totalReply
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.comment {
		padding: 30rpx;
		padding-bottom: 120rpx;

		.item {
			padding: 10rpx 0;
		}
	}
</style>